<template>
    <div class="authority">
        <div class="gva-search-box">
            <el-form ref="searchForm" :inline="true">
                <el-form-item label="巡查系统">
                    <el-select v-model.number="searchInfo.checkOptionId" placeholder="请选择">
                        <el-option v-for="item in checkOptions" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="巡查类型">
                    <el-select v-model.number="searchInfo.type" placeholder="请选择">
                        <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="search" @click="onSubmit">
                        查询
                    </el-button>
                    <el-button icon="refresh" @click="onReset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="gva-table-box unit">
            <div class="gva-btn-list">
                <el-button type="primary" icon="plus" @click="addUnit">新增频次配置</el-button>
            </div>
            <div class="ant-alert-info">
                <el-popover placement="left-start" :width="350" trigger="click" transition='el-zoom-in-left'>
                    <div class="pop-content">
                        <div class="pop-title">自定义列</div>
                        <div class="check-list">
                            <el-checkbox-group v-model="checkedColumns" @change="handleColumnsChange">
                                <el-checkbox v-for="column in columns" :value="column" :label="column"></el-checkbox>
                            </el-checkbox-group>
                        </div>
                    </div>
                    <template #reference>
                        <div class="anticon">
                            <el-icon size="16" color="#1890ff">
                                <Setting />
                            </el-icon>
                            <div style="margin-left: 2px;">自定义列</div>
                        </div>
                    </template>
                </el-popover>
            </div>
            <el-table :data="tableData" row-key="id">
                <el-table-column type="index" label="序号" width="100" />
                <el-table-column align="left" label="巡查系统" v-if="checkedColumns.includes('巡查系统')">
                    <template #default="scope">
                        <span>{{ formattedData(scope.row.checkOptionId) }}</span>
                    </template>
                </el-table-column>
                <el-table-column align="left" label="巡查类型" v-if="checkedColumns.includes('巡查类型')" show-overflow-tooltip>
                    <template #default="scope">
                        <span>{{ scope.row.type == 1 ? '日常巡查' : '综合巡查' }}</span>
                    </template>
                </el-table-column>
                <el-table-column align="left" label="频次" prop="frequencyTimes" v-if="checkedColumns.includes('频次')">
                    <template #default="scope">
                        <span>{{ scope.row.frequencyTimes }}次/{{ timeList[scope.row.frequencyUnit - 1].name }}</span>
                    </template>
                </el-table-column>
                <el-table-column align="left" label="创建时间" v-if="checkedColumns.includes('创建时间')">
                    <template #default="scope">
                        {{ formatTimestamps(scope.row.createdAt) }}
                    </template>
                </el-table-column>
                <el-table-column align="left" label="修改时间" prop="updatedAt" v-if="checkedColumns.includes('修改时间')">
                    <template #default="scope">
                        {{ formatTimestamps(scope.row.updatedAt) }}
                    </template>
                </el-table-column>
                <el-table-column align="left" label="创建人" prop="createUser"
                    v-if="checkedColumns.includes('创建人')"></el-table-column>
                <el-table-column align="left" label="启用状态" v-if="checkedColumns.includes('启用状态')" width="200">
                    <template #default="scope">
                        <el-switch v-model="scope.row.startStatus" size="large" :active-value="1" :inactive-value="2"
                            active-text="启用" inactive-text="禁用" @change="(e) => statusChange(scope.row.id, e)" />
                    </template>
                </el-table-column>
                <el-table-column align="left" fixed="right" label="操作" min-width="140"
                    v-if="checkedColumns.includes('操作')">
                    <template #default="scope">
                        <el-button type="primary" link icon="edit" @click="editUnit(scope.row)" v-if="scope.row.startStatus==2">
                            编辑
                        </el-button>
                        <el-button type="danger" link icon="delete" @click="delUnit(scope.row)" v-if="scope.row.startStatus==2">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="gva-pagination">
                <el-pagination v-model:current-page="page" :page-size="pageSize" :total="total"
                    layout="prev, pager, next" @current-change="handleCurrentChange" />
            </div>
        </div>
        <el-drawer v-model="dialogFormVisible" :size="1000" :before-close="handleClose" :show-close="false">
            <template #header>
                <div class="flex justify-between items-center">
                    <span class="text-lg">{{ dialogTitle }}</span>
                    <div>
                        <el-button @click="closeDialog">取消</el-button>
                        <el-button type="primary" @click="enterDialog">确定</el-button>
                    </div>
                </div>
            </template>
            <el-form v-if="dialogFormVisible" ref="yyglForm" label-width="150" :model="form" :rules="rules">
                <el-form-item label="巡查系统" prop="checkOptionId" v-if="isEdit">
                    <el-select v-model="form.checkOptionId" placeholder="请选择" style="width: 430px;">
                        <el-option v-for="item in checkOptions" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="巡查系统" prop="checkOptionIds" v-else>
                    <el-select v-model="form.checkOptionIds" multiple placeholder="请选择" style="width: 430px;">
                        <el-option v-for="item in checkOptions" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="巡查类型" prop="type">
                    <el-select v-model="form.type" placeholder="请选择" style="width: 430px;">
                        <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="巡查频次" prop="frequencyUnit">
                    <el-select v-model="form.frequencyTimes" placeholder="请选择" style="width: 200px;">
                        <el-option v-for="item in numList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                    <span style="margin: 0 10px;">次/</span>
                    <el-select v-model.number="form.frequencyUnit" placeholder="请选择" style="width: 200px;">
                        <el-option v-for="item in timeList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
            </el-form>
        </el-drawer>
    </div>
</template>
<script setup>
import {
    optionList,
    frequencyAdd,
    frequencyEdit,
    frequencyList,
    frequencyDelete,
    frequencyStart
} from '@/api/yewuguanli'

import { reactive, ref, onMounted } from 'vue'
import { useAppStore } from "@/pinia";
import { useUserStore } from '@/pinia/modules/user'
import { countdownEmits, ElMessage, ElMessageBox, useFormItem } from 'element-plus'
import { formatTimestamps } from '@/utils/format'
const { formItem } = useFormItem()

defineOptions({
    name: 'Yygl'
})
const appStore = useAppStore()
const form = ref({
    checkOptionIds: [],
    frequencyTimes: 1,
    frequencyUnit: 1,
    type: 1,
    frequencyId: '',
    checkOptionId: ''
})

const searchInfo = ref({
    checkOptionId: '',
    type: ''
})

const typeList = ref([
    {
        name: '日常巡查',
        id: 1
    },
    {
        name: '综合巡查',
        id: 2
    }
])
const numList = ref([
    {
        name: 1,
        id: 1
    },
    {
        name: 2,
        id: 2
    },
    {
        name: 3,
        id: 3
    },
    {
        name: 4,
        id: 4
    }
])
const timeList = ref([
    {
        name: '日',
        id: 1
    },
    {
        name: '月',
        id: 2
    },
    {
        name: '年',
        id: 3
    },
    {
        name: '两年',
        id: 4
    },
    {
        name: '三年',
        id: 5
    },
    {
        name: '五年',
        id: 6
    }
])
const userStore = useUserStore()

const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const dialogFormVisible = ref(false)

const rules = reactive({
    checkOptionIds: [{ required: true, message: '请选择巡查系统', trigger: 'change' }],
    checkOptionId: [{ required: true, message: '请选择巡查系统', trigger: 'change' }],
    type: [{ required: true, message: '请选择巡查类型', trigger: 'change' }],
    frequencyUnit: [{ required: true, message: '请选择巡查频次', trigger: 'change' }],
})

const yyglForm = ref(null)

const initForm = () => {
    yyglForm.value.resetFields()
    form.value = {
        checkOptionIds: [],
        frequencyTimes: 1,
        frequencyUnit: 1,
        type: 1,
        frequencyId: '',
        checkOptionId: ''
    }
}

const checkedColumns = ref(['序号', '巡查系统', '巡查类型', '频次', '创建时间', '修改时间', '创建人', '启用状态', '操作'])

if (localStorage.getItem('columnData') && JSON.parse(localStorage.getItem('columnData')).xcpc) {
    checkedColumns.value = JSON.parse(localStorage.getItem('columnData')).xcpc
}
const columns = ref(['序号', '巡查系统', '巡查类型', '频次', '创建时间', '修改时间', '创建人', '启用状态', '操作'])
const handleColumnsChange = (val) => {
    let obj = {

    }
    if (localStorage.getItem('columnData')) {
        obj = JSON.parse(localStorage.getItem('columnData'))
    }
    obj.xcpc = val
    localStorage.setItem('columnData', JSON.stringify(obj))
}
const isEdit = ref(false)
const dialogTitle = ref('新建巡查频次配置')
const addUnit = () => {
    dialogTitle.value = '新建巡查频次配置'
    isEdit.value = false
    dialogFormVisible.value = true
}
const closeDialog = () => {
    initForm()
    dialogFormVisible.value = false
}

const handleClose = (done) => {
    initForm()
    done()
}
const handleUserClose = (done) => {
    initUserForm()
    done()
}
const handleCurrentChange = (val) => {
    page.value = val
    getTableData()
}
const tableData = ref([])
// 查询
const getTableData = async () => {
    const res = await frequencyList({
        pageNumber: page.value,
        pageSize: pageSize.value,
        ...searchInfo.value
    })
    if (res.code == 200) {
        tableData.value = res.result
        total.value = res.result.length
    }
}
getTableData()
const qdCate = ref([
    {
        label: '统信UOS',
        value: 1
    },
    {
        label: '银河麒麟',
        value: 2
    },
    {
        label: '中标麒麟',
        value: 3
    },
    {
        label: 'Windows',
        value: 4
    }
])
const checkOptions = ref([])

onMounted(() => {
    optionList().then(res => {
        checkOptions.value = res.result
    })
})
function formattedData(id) {
    let res = ''
    let obj = checkOptions.value.find(item => item.id == id)
    if (obj) {
        res = obj.name
    }
    return res
}
const enterDialog = async () => {
    yyglForm.value.validate(async (valid) => {
        if (valid) {
            let res
            if (isEdit.value) {
                res = await frequencyEdit(form.value)
            } else {
                form.value.checkOptionIds = form.value.checkOptionIds.join(',')
                res = await frequencyAdd(form.value)
            }
            if (res.code == 200) {
                ElMessage({
                    type: 'success',
                    message: isEdit.value ? '编辑成功' : '添加成功!'
                })
                getTableData()
            }
            initForm()
            dialogFormVisible.value = false
        }
    })
}
const editUnit = async (row) => {
    isEdit.value = true
    dialogTitle.value = '编辑巡查频次配置'
    form.value = JSON.parse(JSON.stringify(row))
    form.value.frequencyId = form.value.id
    dialogFormVisible.value = true
}
const delUnit = (row) => {
    ElMessageBox.confirm(
        '确认删除?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        const res = await frequencyDelete(row.id)
        if (res.code === 200) {
            ElMessage({
                type: 'success',
                message: '删除成功!'
            })
            getTableData()
        }
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消删除'
        })
    })
}
const onSubmit = () => {
    page.value = 1
    getTableData()
}
const onReset = () => {
    page.value = 1
    searchInfo.value = {
        checkOptionId: '',
        type: ''
    }
    getTableData()
}
const dialog2 = ref(false)
function handleClose2() {
    dialog2.value = false
}
function closeDialog2() {
    dialog2.value = false
}
function confirm2() {
    dialog2.value = false
}
function handleSelectionChange(val) {
    form.value.units = val.map(item => item.name).join(',')
    form.value.unitIds = val.map(item => item.id).join(',')
}
function openUnit() {
    dialog2.value = true
}
function reset() {

}
const unitStatusData = ref([])
const dialog3 = ref(false)
const statusTitle = ref('已完成数')
function showDialog3(row, status) {
    if (status == 1) {
        statusTitle.value = '已完成数'
        unitStatusData.value = row.completeUnit || []
    } else {
        statusTitle.value = '未完成数'
        unitStatusData.value = row.notCompleteUnit || []
    }
    dialog3.value = true
}
function handleClose3() {
    dialog3.value = false
}
function closeDialog3() {
    dialog3.value = false
}
function statusChange(id, val) {
    frequencyStart(id).then(res => {
        if (res.code == 200) {
            ElMessage({
                type: 'success',
                message: '状态修改成功!'
            })
            getTableData()
        }
    })
}
</script>

<style lang="scss">
.flex {
    .area {
        flex: 2;
        background-color: #fff;
        margin: 0.5rem 20px 0.5rem 0;
    }

    .unit {
        flex: 4;
    }
}

.ant-alert-info {
    display: flex;
    justify-content: end;
    align-items: center;
    background-color: #e6f7ff;
    border: 1px solid #91d5ff;
    color: #1890ff;
    padding: 5px;

    .anticon {
        display: flex;
        align-items: center;
        cursor: pointer;
    }
}

.btns {
    display: flex;
}

.section-title {
    font-weight: bold;
    font-size: 20px;
    line-height: 33px;
    padding: 8px 0 4px 14px;
    color: #4E7DFD;
    position: relative;
}

.section-title:before {
    content: '';
    position: absolute;
    top: 17px;
    left: 0;
    width: 6px;
    height: 14px;
    border-radius: 3px;
    background: #4E7DFD;
}

.tips {
    margin-bottom: 20px;
    color: #ff6666;
    margin-left: 10px;
}
</style>